package com.fujimana.android.manacode.loalder;

import java.io.File;

public class LoaderFactory {

	private static final LoaderFactory INSTANCE = new LoaderFactory();

	private LoaderFactory() {
		// nothing to do.
	}

	public static LoaderFactory getInstance() {
		return INSTANCE;
	}

	public Sources getSources(String file, String encoding, Filter filter) {
		Sources sources = null;

		if (new File(file).isDirectory()) {
			sources = new SourcesDirectory(file, encoding);
		} else {
			sources = new SourcesArchive(file, encoding);
		}

		sources.setFilter(filter);

		return sources;
	}

	public Sources getSources(String file, String encoding) {
		return getSources(file, encoding);
	}

	public Sources getSources(String file, Filter filter) {
		return getSources(file, null, filter);
	}

	public Sources getSources(String file) {
		return getSources(file, null, null);
	}

	public Tree<String> getTree(Sources sources) {
		Tree<String> tree = new Tree<String>(null);
		tree.setValue("");

		for (String str : sources.getEntries()) {
			prepareTree(str, tree);
		}

		return tree;
	}

	private void prepareTree(String str, Tree<String> tree) {
		String[] list = str.split("\\/");

		Tree<String> t = tree;
		for (int i = 0; i < list.length; i++) {
			String s = list[i];

			Tree<String> find = null;
			for (Tree<String> child : t.getChildlen()) {

				if (child.getValue().equals(s)) {
					find = child;
					break;
				}
			}

			if (find != null) {
				t = find;
			} else {
				createTree(list, i, t);
				break;
			}

		}
	}

	private void createTree(String[] list, int index, Tree<String> tree) {

		Tree<String> t = tree;
		for (int i = index; i < list.length; i++) {
			String str = list[i];

			Tree<String> newTree = new Tree<String>(t);
			newTree.setValue(str);
			t.addChild(newTree);

			t = newTree;
		}
	}
}
